package com.sduept.nwld.dataserver.manager.fault;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.UploadedFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sduept.bigdata.fault.entity.FaultRecordAttachment;
import com.sduept.bigdata.fault.manager.FaultRecordAttachmentManager;
import com.sduept.bigdata.fault.system.properties.FaultSystemProperties;
import com.sduept.generator.ObjectId;
import com.sduept.utils.ZipUtil;

/**
 * 故障附件的上传，下载，删除，查找辅助类
 */
@Service
public class FaultRecordAttachmentAssistManager {

	@Autowired
	private FaultRecordAttachmentManager fram;
	@Autowired
	private FaultSystemProperties pros;
	/**
	 * 图片后缀名
	 */
	public static final List<String> IMGSUFFIXS = Arrays.asList(".png", ".jpg", ".gif");

	/**
	 * 返回下载的文件流
	 * 
	 * @param attachments
	 * @return 可能为null
	 */
	public StreamedContent getAttachmentFile(List<FaultRecordAttachment> attachments) {
		StreamedContent file = null;
		String tmp = ObjectId.get().toString();
		if (attachments == null || attachments.size() == 0) {

		} else if (attachments.size() == 1) {
			FaultRecordAttachment recordAttachment = attachments.get(0);
			InputStream stream = null;
			File f = new File(pros.getFaultAttachmentPath() + recordAttachment.getPath());
			if (!f.exists()) {
				return file;
			}
			try {
				stream = new FileInputStream(pros.getFaultAttachmentPath() + recordAttachment.getPath());
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			}
			HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
					.getRequest();
			try {
				String agent = request.getHeader("User-Agent").toLowerCase();
				if (agent != null
						&& (agent.indexOf("msie") != -1
								|| (agent.indexOf("rv") != -1 && agent.indexOf("firefox") == -1))
						|| agent.indexOf("edge") != -1) {
					file = new DefaultStreamedContent(stream, "application/octet-stream",
							URLEncoder.encode(recordAttachment.getName(), "UTF-8"));
				} else {
					//file = new DefaultStreamedContent(stream, "application/octet-stream",new String(recordAttachment.getName().getBytes("UTF-8"), "ISO8859-1"));
					file = new DefaultStreamedContent(stream, "application/octet-stream",recordAttachment.getName());
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		} else {
			String tmpDir = pros.getDownloadTmPath() + tmp;
			String tmpPath = tmpDir + ".zip";
			List<File> list = new ArrayList<File>();
			// 生成zip文件，需要建立一个文件夹存放缓存数据
			for (FaultRecordAttachment attachment : attachments) {
				String targetPath = tmpDir + File.separator + attachment.getName();
				String filePath = pros.getFaultAttachmentPath() + attachment.getPath();
				File f = new File(filePath);
				if (f.exists()) {
					copyFile(filePath, targetPath);
					list.add(new File(targetPath));
				}
			}
			ZipUtil.zipFile(tmpPath, list);
			ZipUtil.deletefile(tmpDir);
			InputStream stream;
			try {
				stream = new FileInputStream(new File(pros.getDownloadTmPath() + tmp + ".zip"));
				file = new DefaultStreamedContent(stream, "application/octet-stream", tmp + ".zip");
				new DeleteThread(tmpPath).start();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
		return file;
	}

	private static void copyFile(String source1, String target1) {
		File source = new File(source1);
		File target = new File(target1);
		FileInputStream fis = null;
		FileOutputStream fos = null;
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		byte[] ch = new byte[1024 * 1024];
		int len = 0;
		try {
			// 创建流对象
			fis = new FileInputStream(source);
			// 创建缓冲流
			bis = new BufferedInputStream(fis);
			if (!target.exists()) {
				target.getParentFile().mkdirs();
				target.createNewFile();
			}
			fos = new FileOutputStream(new File(target1));
			bos = new BufferedOutputStream(fos);
			while ((len = bis.read(ch)) != -1) {
				bos.write(ch, 0, len);
			}
			// 刷新缓冲区
			bos.flush();

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fis.close();
				bis.close();
				fos.close();
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private class DeleteThread extends Thread {
		String tempPath = "";

		DeleteThread(String tempPath) {
			this.tempPath = tempPath;
		}

		@Override
		public void run() {
			boolean flag = true;
			while (flag) {
				File f = new File(tempPath);
				if (f.exists()) {
					f.delete();
				} else {
					flag = false;
				}
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 删除附件
	 * 
	 * @param attachments
	 * @return
	 */
	public boolean deleteAttachment(List<FaultRecordAttachment> attachments) {
		if (attachments == null) {
			return false;
		}
		for (FaultRecordAttachment a : attachments) {
			File f = new File(pros.getFaultAttachmentPath() + a.getPath());
			if (f.exists()) {
				f.delete();
			}
			fram.deleteById(a.getId());
		}
		attachments.clear();
		return true;
	}

	/**
	 * 上传附件
	 * 
	 * @param event
	 */
	public FaultRecordAttachment handleFileUpload(UploadedFile file, String faultId, String stationId) {
		String fileName = file.getFileName();

		String houzhuiming = fileName.substring(file.getFileName().lastIndexOf("."));
		String id = ObjectId.get().toString();
		String dirFileName = id + houzhuiming;
		String filePath = pros.getFaultAttachmentPath() + dirFileName;
		try {
			FileOutputStream fos = new FileOutputStream(filePath);
			fos.write(file.getContents());
			fos.close();
		} catch (IOException ee) {
			ee.printStackTrace();
		}
		FaultRecordAttachment ra = new FaultRecordAttachment();
		ra.setId(id);
		ra.setName(file.getFileName());
		ra.setPath(dirFileName);
		ra.setFaultId(faultId);
		ra.setStationId(stationId);
		ra.setSuffix(houzhuiming);
		ra.setUploadTime(new Date());
		fram.update(ra);
		return ra;
	}

	public boolean isPicture(String suffix) {
		if (StringUtils.isNotEmpty(suffix) && IMGSUFFIXS.contains(suffix.trim().toLowerCase())) {
			return true;
		}
		return false;
	}

	public String getFullPath(String path) {
		return pros.getFaultAttachmentPath() + path;
	}
}
